<?php
// 声明命名空间
namespace Admin\Controller;

use Admin\Model\UserModel;
use \Frame\Libs\BaseController;

// 定义最终的用户控制器
final class UserController extends BaseController {

    // 列表页：展示用户数据
    public function user_manage() {
        $model = UserModel::getInstance();
        $users = $model->fetchAll();

        
        $this->smarty->caching = false;
        $this->smarty->assign('users', $users);
        $this->smarty->display('index/user_manage.tpl');
    }

    //查询用户
    public function search(){
        $keyword = $_GET['keyword'] ?? '';
        
        // 如果是AJAX请求，返回JSON格式结果
        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
            if (empty($keyword)) {
                echo json_encode(['success' => false, 'message' => '请输入搜索关键词']);
                exit;
            }
            
            $model = UserModel::getInstance();
            // 修复搜索功能，使用正确的searchUsers方法
            $users = $model->searchUsers($keyword);
            
            echo json_encode(['success' => true, 'users' => $users]);
            exit;
        }
        
        // 非AJAX请求的处理逻辑保持不变
        if (empty($keyword)) {
            // 如果没有搜索关键词，重定向到用户管理页面
            //$this->redirect('/admin.php?c=User&a=user_manage');
            return;
        }
        
        $model = UserModel::getInstance();
        // 修复搜索功能，使用正确的searchUsers方法
        $users = $model->searchUsers($keyword);

        $this->smarty->caching = false;
        $this->smarty->assign('users', $users);
        $this->smarty->display('index/user_manage.tpl');
    }

    // 通过AJAX获取用户数据
    public function getUser() {
        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
            $uid = $_GET['id'] ?? 0;
            
            if ($uid > 0) {
                $model = UserModel::getInstance();
                $user = $model->getUserById($uid);
                
                if ($user) {
                    echo json_encode(['success' => true, 'user' => $user]);
                } else {
                    echo json_encode(['success' => false, 'message' => '用户不存在']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => '无效的用户ID']);
            }
            exit;
        }
        // 非AJAX请求直接返回失败
        echo json_encode(['success' => false, 'message' => '非法请求']);
        exit;
    }
    
    // 更新用户 - 展示表单或处理更新
    public function update(){
        // 获取用户ID
        $uid = $_GET['id'] ?? 0;
        
        // 如果是GET请求且有ID，展示编辑表单
        if ($uid > 0 && $_SERVER['REQUEST_METHOD'] == 'GET') {
            $model = UserModel::getInstance();
            $user = $model->getUserById($uid);
            
            if ($user) {
                $this->smarty->assign('user', $user);
                $this->smarty->display('index/user_form.tpl');
            } else {
                //$this->redirect('/admin.php?c=User&a=user_manage');
            }
        } 
        // 如果是GET请求且没有ID，展示新建表单
        else if ($uid == 0 && $_SERVER['REQUEST_METHOD'] == 'GET') {
            $this->smarty->display('index/user_form.tpl');
        }
        // 处理表单提交
        else {

            if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
                // 同时支持GET和POST请求
                $username = $_REQUEST['username'] ?? '';
                $password = $_REQUEST['password'] ?? '';
                $email = $_REQUEST['email'] ?? '';
                $status = $_REQUEST['status'] ?? '1';

                if(empty($username) || empty($email)){
                    echo json_encode(['success' => false, 'message' => '用户名和邮箱不能为空']);
                    exit;
                }
                
                $model = UserModel::getInstance();
                
                if ($uid > 0) {
                    // 更新现有用户
                    $result = $model->updateUser($uid, $username, $password, $email, $status);
                    $message = $result ? '用户更新成功' : '用户更新失败';
                } else {
                    // 创建新用户
                    $result = $model->insertUser($username, $password, $email, $status);
                    $message = $result ? '用户创建成功' : '用户创建失败';
                }

                echo json_encode(['success' => $result, 'message' => $message]);
                exit;
            }
            
            // 非AJAX请求的处理逻辑保持不变
            // 同时支持GET和POST请求
            $username = $_REQUEST['username'] ?? '';
            $password = $_REQUEST['password'] ?? '';
            $email = $_REQUEST['email'] ?? '';
            $status = $_REQUEST['status'] ?? '1';

            if(empty($username) || empty($email)){
                // 可以添加错误信息提示

                return;
            }
            
            $model = UserModel::getInstance();
            
            if ($uid > 0) {
                // 更新现有用户
                $result = $model->updateUser($uid, $username, $password, $email, $status);
            } else {
                // 创建新用户
                $result = $model->insertUser($username, $password, $email, $status);
            }
        }
    }

    //改变用户状态
        public function changeStatus(){
            $uid = $_GET['id'] ?? 0;
            $status = $_GET['status'] ?? '';

            if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
                if ($uid <= 0 || empty($status)) {
                    echo json_encode(['success' => false, 'message' => '参数错误']);
                    exit;
                }
                
                $model = UserModel::getInstance();
                $result = $model->changeStatus($uid, $status);
                $message = $result ? '用户状态更新成功' : '用户状态更新失败';
                
                echo json_encode(['success' => $result, 'message' => $message]);
                exit;
            }
            

        if ($uid <= 0 || empty($status)) {
            return;
        }
        
        $model = UserModel::getInstance();
        $result = $model->changeStatus($uid, $status);
        }

        //删除用户
        public function deleteUser(){
            $id = $_GET['id'] ?? 0;

            if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
                if ($id <= 0) {
                    echo json_encode(['success' => false, 'message' => '参数错误']);
                    exit;
                }
                
                $model = UserModel::getInstance();
                $result = $model->deleteUser($id);
                $message = $result ? '用户删除成功' : '用户删除失败';
                
                echo json_encode(['success' => $result, 'message' => $message]);
                exit;
            }

            if ($id <= 0) {
                return;
            }
            
            $model = UserModel::getInstance();
            $result = $model->deleteUser($id);
        }
        
        // 批量删除用户
        public function batchDelete(){
            $ids = $_GET['ids'] ?? '';

            if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
                if (empty($ids)) {
                    echo json_encode(['success' => false, 'message' => '请选择要删除的用户']);
                    exit;
                }
                
                $model = UserModel::getInstance();
                $result = $model->batchDelete($ids);
                $message = $result ? '用户批量删除成功' : '用户批量删除失败';
                
                echo json_encode(['success' => $result, 'message' => $message]);
                exit;
            }

            if (empty($ids)) {
                return;
            }
            
            $model = UserModel::getInstance();
            $result = $model->batchDelete($ids);
        }

}
